package cuttings;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

import javazoom.jl.player.Player;


public class MP3 {
    private String filename;
    private Player player; 
	private String[] gameBGM = new String[10];
	private static int playlistIndex = 0;

    // constructor that takes the name of an MP3 file
    public MP3(String filename) {
        this.filename = filename;
    }

	public void setPlaylist(String[] playlist) {
		gameBGM = playlist;
		playlistIndex = 0;
	}

    public void stop() { if (player != null) player.close(); }

    // play the MP3 file to the sound card
    public void play(int value) {
	
		// 0 - Play once
		// 1 - Loop filename
		// 2 - Loop through playlist
		
		final int mode=value;

        try {
			FileInputStream fis;  
			if (mode == 2) {
				fis     = new FileInputStream(gameBGM[playlistIndex==gameBGM.length?playlistIndex=0:playlistIndex++]);
			}
            else {
				fis     = new FileInputStream(filename);
			}
            BufferedInputStream bis = new BufferedInputStream(fis);
            player = new Player(bis);
        }
        catch (Exception e) {
            System.out.println("Problem playing file " + filename);
            System.out.println(e);
        }

        // run in new thread to play in background
        new Thread() {
            public void run() {
	
                try { 
					
						player.play(); 
						if (mode !=0) {
							while (!player.isComplete()){};
							play(mode);
						}

					
				}
                catch (Exception e) { System.out.println(e); }
            }
        }.start();
		
	
		
	//	if (player.isComplete()) play();

    }
}